package com.atguigu.gmall.publisher.controller;

import com.atguigu.gmall.publisher.beans.TradeProvinceOrderAmount;
import com.atguigu.gmall.publisher.service.TradeStatsService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author Felix
 * @date 2022/10/13
 * 交易域统计Controller
 */
@RestController
public class TradeStatsController {

    @Autowired
    private TradeStatsService tradeStatsService;

    @RequestMapping("/province")
    public String getProvinceAmount(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        List<TradeProvinceOrderAmount> provinceAmountList = tradeStatsService.getProvinceAmount(date);
        StringBuilder jsonB = new StringBuilder("{\"status\": 0,\"data\": {\"mapData\": [");
        for (int i = 0; i < provinceAmountList.size(); i++) {
            TradeProvinceOrderAmount orderAmount = provinceAmountList.get(i);
            jsonB.append("{\"name\": \"" + orderAmount.getProvinceName() + "\",\"value\": " + orderAmount.getOrderAmount() + "}");
            if(i < provinceAmountList.size() - 1){
                jsonB.append(",");
            }
        }
        jsonB.append("],\"valueName\": \"交易额\"}}");
        return jsonB.toString();
    }

    @RequestMapping("/gmv")
    public String getGMV(@RequestParam(value = "date", defaultValue = "0") Integer date) {
        if (date == 0) {
            date = now();
        }
        BigDecimal gmv = tradeStatsService.getGMV(date);
        String json = "{\"status\": 0,\"data\": " + gmv + "}";
        return json;
    }

    private Integer now() {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
        return Integer.valueOf(yyyyMMdd);
    }
}
